package SVN::TeamTools::Plugins::Browse;

use warnings;
use strict;
use Carp;
use Error qw(:try);

use SVN::TeamTools::Store::Config;
use SVN::TeamTools::Store::Repo;

use HTML::Template;
use CGI;
use URI::Escape;

my $conf;
my $logger;
BEGIN { $conf = SVN::TeamTools::Store::Config->new(); $logger = $conf->{logger}; }

sub hasAction {
        shift;
        my %args        = @_;
        my $action      = $args{action};
        return ("|dsp.browse|get.subtree|" =~ /\|\Q$action\E\|/);
}

sub getTemplate {
	my $cgi = new CGI;
        my $template = HTML::Template->new( filename => 'SVN/TeamTools/Plugins/tmpl/browse.tmpl', path => @INC );
	my $rev = SVN::TeamTools::Store::Repo->new()->getSvnRev();
	$template->param (p_rev		=> $rev);
	$template->param (p_head	=> $rev);
	return $template;
}

sub typeFilter {
        my $indextypes = "txt";
        while (my ($regex, $lang) = each (%{$conf->{src_types}})) {
##                if ('1' == $lang->{index}) {
                        $indextypes="$indextypes|$regex";
##                }
        }
        return $indextypes;
}

sub getData {
        shift;
        my %args        = @_;
        my $param       = $args{param};

	my $repo = SVN::TeamTools::Store::Repo->new();
	my $types = typeFilter();

	my $look = $repo->getLook (rev => $param->{rev});
	my @temptree = $look->tree($param->{path},"--non-recursive", "--full-paths");

	my @tree;
	push (@tree, sort (grep( /\/$/, @temptree)));
	push (@tree, sort (grep( !/\/$/, @temptree)));
	shift (@tree);

	my @result;
	foreach my $path (@tree) {
		$path =~ /([^\/]*\/?)$/;
		my $name = $1;
		my $type = ($name =~ /\/$/) ? "dir" : ( $name =~ /\.$types$/ ) ? "known" : "unknown";

##		my @d_look = $repo->getLook(rev => $param->{rev})->_svnlook("history --limit 1",$param->{path});
		my @d_look = $repo->getLook(rev => $param->{rev})->_svnlook("history --limit 1",$path);
		shift (@d_look);
		shift (@d_look);
	
		my $last_rev_txt = shift (@d_look);
		$last_rev_txt =~ /^\s*([0-9]+)/;
		my $last_rev = $1;
		my $details = $repo->getLook(rev => $last_rev);

		my %obj = (
			name		=> $name,
			path		=> $path,
			type		=> $type,
			last_rev	=> $last_rev,
			last_author	=> $details->author(),
			log_msg		=> $details->log_msg(),
			date		=> $details->date(),
		);
		push (@result, \%obj);
	}
	return \@result;
}
1;
